using System.Data.SQLite;
using System.Security.Cryptography;
using System.Text;
public class DatabaseHelper
{
    public void CreateDatabaseAndTable()
    {
        SQLiteConnection.CreateFile("MyDatabase.sqlite");

    using (SQLiteConnection conn = new SQLiteConnection("data source=MyDatabase.sqlite"))
    {
        conn.Open();

        using (SQLiteCommand cmd = new SQLiteCommand(conn))
        {
            cmd.CommandText = @"CREATE TABLE Users(
                                Username TEXT PRIMARY KEY,
                                Password TEXT NOT NULL);";
            cmd.ExecuteNonQuery();
        }
    }
    }

    public void InsertUser(string username, string password)
    {
        using (SQLiteConnection conn = new SQLiteConnection("data source=MyDatabase.sqlite"))
    {
        conn.Open();

        using (SQLiteCommand cmd = new SQLiteCommand(conn))
        {
            cmd.CommandText = "INSERT INTO Users(Username, Password) VALUES (@Username, @Password)";
            cmd.Parameters.AddWithValue("@Username", username);
            cmd.Parameters.AddWithValue("@Password", password);
            cmd.ExecuteNonQuery();
        }
    }
    }

    public bool ValidateUser(string username, string password)
    {
        string passwordHash = ComputeSha256Hash(password);
         using (SQLiteConnection conn = new SQLiteConnection("data source=MyDatabase.sqlite"))
    {
        conn.Open();

        using (SQLiteCommand cmd = new SQLiteCommand(conn))
        {
            cmd.CommandText = "SELECT * FROM Users WHERE Username = @Username AND Password = @Password";
            cmd.Parameters.AddWithValue("@Username", username);
            cmd.Parameters.AddWithValue("@Password", passwordHash);

            using (SQLiteDataReader reader = cmd.ExecuteReader())
            {
                return reader.HasRows;
            }
        }
    }
    }

    private string ComputeSha256Hash(string rawData)
    {
         using (SHA256 sha256Hash = SHA256.Create())
    {
        byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < bytes.Length; i++)
        {
            builder.Append(bytes[i].ToString("x2"));
        }

        return builder.ToString();
    }
}
    }
}